<?php

namespace common\entities\myhtsq;

use common\repositories\myhtsq\ContractPayoverRepository;
use common\repositories\myhtsq\ContractRevenueRepository;
use Yii;

/**
 * This is the model class for table "myscrm_contract_revenue".
 *
 * @property string $revenue_id
 * @property string $contract_id
 * @property string $revenue_type
 * @property string $amount
 * @property string $created_on
 * @property string $created_by
 * @property string $modified_on
 * @property string $modified_by
 * @property int $close_status
 */
class ContractRevenueEntity extends \common\entities\ConfigEntity
{


	public $type_name;


    /**
     * 收入项操作动作
     */
    const OPERATE_ADD = 'add';
    const OPERATE_EDIT = 'edit';

    /**
     * 关闭状态
     */
    const CLOSE_STATUS_NOT = 0; //未关闭
    const CLOSE_STATUS_AUTO = 1;   //自动关闭

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'myscrm_contract_revenue';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['revenue_id'], 'required'],
            [['amount'], 'number'],
            [['created_on', 'modified_on'], 'safe'],
            [['revenue_id', 'contract_id', 'created_by','revenue_type', 'modified_by'], 'string', 'max' => 36]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'revenue_id' => '收入ID',
            'contract_id' => '合同ID',
            'revenue_type' => '收入类型',
            'amount' => '金额',
            'created_on' => '创建时间',
            'created_by' => '创建人',
            'modified_on' => '修改时间',
            'modified_by' => '修改人',
        ];
    }
    
    /**
     * 根据合同id,获取收入信息
     * @param string $contractId 合同id
     * @return array
     */
    public static function getContractRevenueListByContractId($contractId) {
    	return self::find()->where(['contract_id'=>$contractId])->all();
    }
    
    /**
     * 根据收入id 删除收入信息
     * @param string $revenueId
     * @return boolean
     */
    public static function deleteContractRevenueByRevenueId($revenueId) {
    	return self::deleteAll(['revenue_id'=>$revenueId]);
    }

    /**
     * 收入项生成检查
     * @param $action
     * @return bool
     * @throws \Exception
     */
    public function generateCheck($action){
        if($this->contract_id){
            $contract_balance_amount = ContractPayoverRepository::getApplicationPayOverAmountSum($this->contract_id);//合同收入项金额
            $contract_income_amount = ContractRevenueRepository::getContractRevenueSumByContractId($this->contract_id);//已生成的收入项金额
            if($action == self::OPERATE_ADD){
                if($contract_balance_amount - $contract_income_amount >= $this->amount){
                    return true;
                }
                throw new \Exception('待生成的收入项不满足生成条件 ：合同总的结算金额【'.$contract_balance_amount .'】-已生成的收入项金额【'.$contract_income_amount.'】不应小于本次新增的金额【'.$this->amount.'】');
            }elseif($action == self::OPERATE_EDIT){
                if($this->close_status == self::CLOSE_STATUS_AUTO){
                    $check = $this->closeCheck();
                    if(!$check){
                        throw new \Exception('此收入项不满足关闭条件');
                    }
                    return $check;
                }
                $old_revenue_amount = $this->getOldAttribute('amount');
                if($contract_balance_amount - ($contract_income_amount- $old_revenue_amount) >= $this->amount){
                    return true;
                }
                throw new \Exception('待生成收入项【'.$this->amount.'】+' . '已生成收入项【'.($contract_income_amount- $old_revenue_amount).'】不应大于合同总的结算金额【'.$contract_balance_amount.'】');
            }
        }
        return true;
    }

    /**
     * 关闭收入项检查
     */
    public function closeCheck(){
        if($this->revenue_id && ($this->close_status == self::CLOSE_STATUS_AUTO)){
            $revenue_amount = $this->amount;//当前收入项需转结的金额
            $totalConfirmedAmount = ContractRevenueRepository::getTotalConfirmedAmount($this->revenue_id);//当前收入项所属的总的已确认金额
            $latestCarryOver = ContractRevenueRepository::getLatestCarryoverByRevenueId($this->revenue_id);//最近一次转结
            $unConfirmedAmount = $revenue_amount - $totalConfirmedAmount;
            $condition_1 = ($unConfirmedAmount == 0 || $unConfirmedAmount - $this->no_confirm_bad_amount == 0);
            $condition_2 = ($revenue_amount == $totalConfirmedAmount + $unConfirmedAmount + $this->no_confirm_bad_amount);
            $condition_3 = ($latestCarryOver->this_period_confirm_total_amount == $latestCarryOver->this_period_confirm_amount + $latestCarryOver->last_period_total_confirm_amount);
            if($condition_1 === false){
                Yii::info('收入项'.$this->revenue_id.'条件1不满足:(待确认收入)'.$unConfirmedAmount .'= 0 或者 (未确认已发生坏账)'.$this->unrecognized_bad_debt_amount .'-(待确认金额)'.$unConfirmedAmount,'carry_over_log');
            }
            if($condition_2 === false){
                Yii::info('收入项'.$this->revenue_id.'条件2不满足:(收入项金额)'.$revenue_amount .'==(当期累计确认收入)'.$totalConfirmedAmount.'+(待确认金额)'.$unConfirmedAmount.'+(未确认收入已发生坏账)'.$this->unrecognized_bad_debt_amount,'carry_over_log');
            }
            if($condition_3 === false){
                Yii::info('收入项'.$this->revenue_id.'条件3不满足:(当期累计确认收入)'.$latestCarryOver->this_period_confirm_total_amount.'=(当期确认收入)'.$latestCarryOver->this_period_confirm_amount.'+(上期累计确认收入)'.$latestCarryOver->last_period_total_confirm_amount,'carry_over_log');
            }
            if($condition_1 && $condition_2 && $condition_3){
                return true;
            }
            return false;
        }
        return true;
    }

    /**
     * @param $carry_over_data
     * @return bool
     */
    public function carryOverCheck($carry_over_data){
        if($this->revenue_id){
            $revenue_amount = $this->amount;//当前收入项需转结的金额
            $totalConfirmedAmount = ContractRevenueRepository::getTotalConfirmedAmount($this->revenue_id);//当前收入项所属的总的已确认金额
            $latestCarryOver = ContractRevenueRepository::getLatestCarryoverByRevenueId($this->revenue_id);//所有的转结
            $unConfirmedAmount = $revenue_amount - $totalConfirmedAmount;

            //转结一次以上才会校验    上期的当期累计确认收入=当期的上期累计收入
            if(empty($latestCarryOver)){
                $condition_1 = true;
            }else{
                $condition_1 = ($latestCarryOver->this_period_confirm_total_amount == $carry_over_data['last_period_total_confirm_amount'])?true:false;
            }
            $condition_2 = ($revenue_amount == $totalConfirmedAmount + $unConfirmedAmount + $this->no_confirm_bad_amount)?true:false;
            $condition_3 = (round($carry_over_data['this_period_confirm_total_amount'],2) == round($carry_over_data['this_period_confirm_amount']+$carry_over_data['last_period_total_confirm_amount'],2))?true:false;

            if($condition_1 === false){
                Yii::info('收入项'.$this->revenue_id.'条件1不满足:(上期的当期累计确认收入)'.$latestCarryOver->this_period_confirm_total_amount .'=(当期的上期累计确认收入)'.$carry_over_data['last_period_total_confirm_amount'],'carry_over_log');
            }
            if($condition_2 === false){
                Yii::info('收入项'.$this->revenue_id.'条件2不满足:(收入项金额)'.$revenue_amount .'==(当期累计确认收入)'.$totalConfirmedAmount.'+(待确认金额)'.$unConfirmedAmount.'+(未确认收入已发生坏账)'.$this->unrecognized_bad_debt_amount,'carry_over_log');
            }
            if($condition_3 === false){
                Yii::info('收入项'.$this->revenue_id.'条件3不满足:(当期累计确认收入)'.round($carry_over_data['this_period_confirm_total_amount'],2).'=(上期累计确认收入)'.round($carry_over_data['this_period_confirm_amount'],2).'+(当期确认收入)'.$carry_over_data['last_period_total_confirm_amount'],'carry_over_log');
            }
            if($condition_1 && $condition_2 && $condition_3){
                return true;
            }
            return false;
        }
        return true;
    }



}
